package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.common.core.enums.OrderStateEnum;
import com.etoak.common.web.context.LoginUserContext;
import com.etoak.config.OrderQueueConfig;
import com.etoak.dto.OrderDTO;
import com.etoak.entity.Order;
import com.etoak.entity.OrderItem;
import com.etoak.mapper.OrderItemMapper;
import com.etoak.mapper.OrderMapper;
import com.etoak.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * OrderService
 *
 * @author etoak
 * @since 2025-02-07
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 创建订单
     * @param orderDTO 订单参数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void create(OrderDTO orderDTO) {

        /**
         * 创建order对象 添加订单表
         */
        Order order=new Order();
        //订单编号 有序的字符唯一的
        String orderNo = IdUtil.getSnowflakeNextIdStr();

        order.setOrderNo(orderNo);
        order.setUserId(Integer.parseInt(LoginUserContext.getUserId()));
        order.setOrderState(OrderStateEnum.CREATE.getState());
        order.setCreateTime(DateUtil.now());
        order.setPrepareTime(orderDTO.getPrepareTime());
        this.save(order);
        /**
         * 创建订单项列表 添加到订单详表
         */
        List<OrderItem> orderItemList = orderDTO.getItemList().stream().peek(item -> item.setOrderNo(orderNo)).toList();

        orderItemMapper.batchInsert(orderItemList);

        rabbitTemplate.convertAndSend(OrderQueueConfig.EXCHANGE,
                OrderQueueConfig.KEY,
                orderNo,
                message->{
                    message.getMessageProperties().setDelayLong(10000L);
                    return message;
                });

    }
}
